import Axios from 'axios'
import { Dialog } from "vant";

import route from "../router/index";
// 正式
// const baseURL = process.env.NODE_ENV === "development" ? "https://www.xuhe.art/" : "https://www.xuhe.art/"
// 测试
const baseURL = process.env.NODE_ENV === "development" ? "/" : "/abe"
class HttpRequest {
  constructor() {
    this.options = {
      url: '/abeProduct/selectLitByProductId',
      data:{}
    }
    // 存储请求队列
    this.queue = {}
  }
  // 销毁请求实例
  destroy(url) {
    delete this.queue[url]
    const queue = Object.keys(this.queue)
    return queue.length
  }
  // 请求拦截
  interceptors(instance, url) {
    // 添加请求拦截器
    instance.interceptors.request.use(
      config => {
        // 在发送请求之前做些什么
        return config
      },
      error => {
        // 对请求错误做些什么
        return Promise.reject(error)
      }
    )

    // 响应拦截
    instance.interceptors.response.use(res => {
      this.destroy(url)
      const { data, status } = res
      if (res.data?.code === 400 || res.data?.code === 500) {
        if (res.data.msg) {
          Dialog.alert({
            title: "提示",
            message: res.data.msg
          });
        }
        return Promise.reject(data)
      } else if (res.data && res.data?.code === 401) {
      }
      return { data, status }
    }, error => {
      console.log(error)
      this.destroy(url)
      return Promise.reject(error)
    })
  }
  // 创建实例
  create(header) {
    let conf = {
      baseURL: baseURL,
      timeout: 6000,
      method: 'POST',
      headers: {
        'Content-Type': 'application/json; charset=utf-8',
        'Cache-Control': 'no-cache',
        ...header
      }
    }
    return Axios.create(conf)
  }

  // 请求实例
  request(options) {
    var instance = this.create()
    this.interceptors(instance, options.url)
    console.log(options);
    options = Object.assign({}, options)
    this.queue[options.url] = instance
    return instance(options)
  }
}

const axiosUpload = new HttpRequest()
export default axiosUpload;

